package com.controller;


import com.entities.CommonResult;
import com.entities.Payment;
import com.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.awt.event.WindowFocusListener;
import java.util.List;

/**
 * Description: 支付控制类
 *
 * @Autor: Rolin
 * datetime: 04-23-15:35
 */

@RestController
@Slf4j
public class PaymentController {

    @Autowired
    PaymentService paymentService;

    @Resource
    private DiscoveryClient discoveryClient;

    @Value("${server.port}")
    private String serverPort;

    @PostMapping("/payment/insert")
//    注意，单一启动需要吧@RequestBody 注解去掉.
    public CommonResult<Payment> create( @RequestBody Payment payment){
        int result = paymentService.insert(payment);
        if(result>0){
            return new CommonResult("执行成功,serverPort="+serverPort,200, payment);
        }else {
            return new CommonResult("执行失败",444,null);
        }
    }

    @GetMapping("/payment/get/{id}")
    public CommonResult getById(@PathVariable("id")Integer id){
        Payment payment = paymentService.selectById(id);
        if (payment==null){
            return new CommonResult("执行失败",444,null);
        }else {
            return new CommonResult("执行成功,serverPort="+serverPort,200,payment);
        }
    }

    @GetMapping("/payment/discovery")
    public Object discovery(){
        //显示所有注册到eureka中的client
        List<String> services = discoveryClient.getServices();
        services.forEach(service -> log.info(service));

        //显示指定 名称的client
        List<ServiceInstance> instances = discoveryClient.getInstances("PAYMENT-CLIENT");
        instances.forEach(instance -> log.info(instance.getHost()+"\t"+instance.getInstanceId()+"\t"+instance.getPort()
        +"\t"+instance.getUri()));

        return this.discoveryClient;
    }


    //    这里测试ribbon自定义轮询负载均衡算法
    @GetMapping("/payment/lb")
    public String testForRibbon(){
        //此处就返回个端口号用于测试
        return serverPort ;
    }

    //这里测试openFeign的超时配置,openfeign的默认链接时间是1s,超过1s报错；
    @GetMapping("/payment/timeout")

    public String openFeignTest01(){
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }

}
